package com.zzyl.service.impl;

import cn.hutool.jwt.JWTUtil;
import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.entity.Member;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.properties.JwtConfigProperties;
import com.zzyl.service.MemberService;
import com.zzyl.service.WeChatService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/*
   @ApiModelProperty("昵称")
    private String nickName;

    @ApiModelProperty("登录临时凭证")
    private String code;

    @ApiModelProperty("手机号临时凭证")
    private String phoneCode;

 */
@Service
@Transactional
public class MemberServiceImpl implements MemberService {
    @Autowired
    WeChatService weChatService;

    @Autowired
    MemberMapper memberMapper;
    @Override
    public LoginVo login(UserLoginRequestDto userDto) {
        //通过code和id和secret获取openId
        String openId=weChatService.getOpenId(userDto.getCode());
        //通过id和secret获取access_token access_token是获取手机号的的参数之一
        //然后通过access_token和phonecode获取手机号
        String phone=weChatService.getPhone(userDto.getPhoneCode());

        //1.通过openID判断有没有在后端注册过
        Member member=memberMapper.getByOpenId(openId);


        //1.1注册过
        if(!Objects.isNull(member)){
            //1.1.1判断手机号是否相等
            if(!ObjectUtil.equals(phone,member.getPhone())) {
                //1.1.2 不相等 update数据库
                member.setPhone(phone);
                memberMapper.update(phone);

            }
        }else{
            //1.2 没注册过 新增 记得插入nickName
            member=new Member();
            member.setPhone(phone);
            member.setName("哈哈哈");
            member.setOpenId(openId);

            memberMapper.insert(member);

        }


        //创建jwt 返回jwt
        Map<String,Object> map=new HashMap<>();
        map.put("id",member.getId());
//        JwtConfigProperties jwtConfigProperties=new JwtConfigProperties();
//        System.out.println(jwtConfigProperties.getTtl());
//        System.out.println(jwtConfigProperties.getBase64EncodedSecretKey());
        String token = JwtUtil.createJWT("$2a$10$PVtHnkj86mJgf6li/yron.LRx/cQAlaiZkBJ9BeogCNTryXJRT1YC", 3600000, map);
        LoginVo loginVo=new LoginVo();
        loginVo.setNickName("哈哈哈");
        loginVo.setToken(token);
        return loginVo;
    }
}
